<template>
  <a-table
    v-if="dataSource"
    class="table"
    :columns="columns"
    :dataSource="dataSource"
    :pagination="false"
    :scroll="{
      scrollToFirstRowOnChange: true,
      x: '100%',
    }"
    rowKey="id"
    defaultExpandAllRows
    :sticky="true"
    @resizeColumn="
        (w:number, col: ColumnItem) => {
          col.width = Math.max(w,col.minWidth||0);
        }
      "
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'action' && record.nodeType === 1">
        <a-button type="link" @click="handleIndicatorEdit(record)">{{
          getActionButtonText(record)
        }}</a-button>
      </template>
      <a
        v-else-if="column.dataIndex === 'name' && record.nodeType === 1"
        :href="`/file/indicator/${record.id.replace('I-', '')}/indicator.html`"
        target="_blank"
        :title="record[column.dataIndex]"
        >{{
          column.customRender?.({ text: record[column.dataIndex] }) ||
          record[column.dataIndex]
        }}</a
      >
    </template>
  </a-table>
  <a-button
    v-if="
      (!routeNamePrefix && [200, 500].includes(status)) ||
      (routeNamePrefix === 'Approval' && [450, 600].includes(status))
    "
    type="primary"
    @click="handleSubmit"
    >提交</a-button
  >
</template>
<script lang="ts" setup>
import {
  IndicatorSystemDetailItem,
  getProjectIndicatorsById,
  submitApproval,
  submitFillin,
} from "@/api";
import {
  getFillColumns,
  getApprovalIndicatorColumns,
  getBackendIndicatorColumns,
} from "../config";
import { computed, getCurrentInstance, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
const props = defineProps<{ readOnly: boolean; routeNamePrefix: string }>();
const { $loading } =
  getCurrentInstance()?.appContext?.config.globalProperties || {};
const route = useRoute();
const router = useRouter();
const status = computed(() => +route.params.status);
const columns = ref(
  props.routeNamePrefix === "Approval"
    ? getApprovalIndicatorColumns()
    : props.routeNamePrefix === "Backend"
    ? getBackendIndicatorColumns(status.value)
    : getFillColumns()
);
const dataSource = ref<IndicatorSystemDetailItem[]>();

$loading?.start();
getProjectIndicatorsById(Number(route.params.id))
  .then((res) => {
    dataSource.value = res.indicators;
    if (res.status !== +route.params.status) {
      router.replace({
        name: route.name || "",
        params: {
          ...route.params,
          status: res.status,
        },
      });
    }
  })
  .catch(console.error)
  .finally(() => {
    $loading?.stop();
  });
const handleIndicatorEdit = (record: IndicatorSystemDetailItem) => {
  router.push({
    name: props.routeNamePrefix + "ProjectFillDetail",
    params: Object.assign({}, route.params, {
      indicatorId: record.id.slice(2),
      onlyread:
        (props.routeNamePrefix === "Approval" &&
          !(
            status.value === 450 ||
            (status.value === 600 && record.approvalResult === 2)
          )) ||
        props.routeNamePrefix === "Backend" || // 后台页面
        (!props.routeNamePrefix &&
          (![200, 500].includes(status.value) ||
            (record.approvalStatus === 1 && record.approvalResult !== 2)))
          ? "true"
          : "false",
    }),
  });
};
const handleSubmit = async () => {
  $loading?.start();
  const method =
    props.routeNamePrefix === "Approval" ? submitApproval : submitFillin;
  method(route.params.id as string)
    .then(() => {
      router.push({
        name: props.routeNamePrefix + "Projects",
      });
    })
    .catch(console.error)
    .finally(() => {
      $loading?.stop();
    });
};
const getActionButtonText = (record: Record<string, any>) => {
  if (props.routeNamePrefix === "Approval") {
    return status.value === 450 ||
      (status.value === 600 && record.approvalResult === 2)
      ? "去评审"
      : "查看";
  }
  if (
    props.routeNamePrefix === "Backend" || // 后台页面
    ![200, 500].includes(status.value) ||
    (record.approvalStatus === 1 && record.approvalResult !== 2)
  ) {
    return "查看";
  }
  return status.value === 500 ? "修订" : "填报";
};
</script>
<style lang="scss" scoped>
.ant-select {
  width: 200px;
}
.table {
  margin: 16px 0;
}
</style>
